<template>
  <div class="page-container">
    <CashSearchFrom
      :query="state.query"
      @reset="reset"
      @getList="getList"
      :cashType="'income'"
    ></CashSearchFrom>
    <div
      class="in-container"
      style="margin-top: 8px; height: calc(100% - 180px)"
    >
      <div class="btn-box">
        <el-button type="default" icon="RefreshRight" @click="getList">
        </el-button>
        <el-button
          type="primary"
          @click="
            $router.openTab({ title: '新增收款', path: '/financial/cashnew' })
          "
        >
          新增
        </el-button>
        <el-button type="primary" @click="deleWriteOff"> 删除 </el-button>
        <el-dropdown
          ref="dropdown1"
          trigger="hover"
          style="margin-left: 10px; margin-right: 10px"
          @command="aduitCommand"
        >
          <el-button type="primary"> 审核管理 </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :command="1">
                <div style="min-width: 50px">提交</div>
              </el-dropdown-item>
              <el-dropdown-item :command="2">通过</el-dropdown-item>
              <el-dropdown-item :command="-1">驳回</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button type="primary" @click="downloadFile"> 导出EXCEL </el-button>
      </div>
      <AppPageTable
        stripe
        :data="state.tableData.data"
        @change="getList"
        :autostyle="'height: calc(100% - 50px);'"
        :option="state.tableData.option"
        v-loading="state.tableLoading"
      >
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column
          prop="doccode"
          width="130"
          label="收款单号"
          align="center"
          showOverflowTooltip
        >
          <template #default="scope">
            <span class="doccode-text" @click="toEditPage(scope.row)">{{
              scope.row.doccode
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="审核状态"
          align="center"
          showOverflowTooltip
          width="100"
        >
          <template #default="scope">
            {{
              scope.row.checkStatus == 0
                ? '草拟'
                : scope.row.checkStatus == 1
                ? '提交审核'
                : scope.row.checkStatus == 2
                ? '审核通过'
                : scope.row.checkStatus == -1
                ? '驳回'
                : ''
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="checkTime"
          width="100"
          align="center"
          label="审核日期"
          showOverflowTooltip
        >
          <template #default="scope">
            {{
              scope.row.checkTime
                ? $utils.formatDateTime(scope.row.checkTime, 'YYYY-MM-DD')
                : ''
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="checkBy"
          width="100"
          align="center"
          label="审核人"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="salesName"
          label="业务员"
          align="center"
          width="100"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          label="到账日期"
          align="center"
          showOverflowTooltip
          width="100"
        >
          <template #default="scope">
            {{
              scope.row.docdate
                ? $utils.formatDateTime(scope.row.docdate, 'YYYY-MM-DD')
                : ''
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="entCode"
          label="单位编号"
          align="center"
          width="100"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="entFullname"
          align="center"
          label="单位名称"
          width="100"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          label="类型"
          align="center"
          width="100"
          showOverflowTooltip
        >
          <template #default="scope">
            {{ scope.row.doctype == 1 ? '收款' : '付款' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="currency"
          label="币种"
          align="center"
          width="100"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="canverificationMoney"
          label="销账金额"
          align="center"
          width="100"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="sumverificationMoney"
          label="已销金额"
          align="center"
          showOverflowTooltip
          width="100"
        >
        </el-table-column>
        <el-table-column
          prop="xunVerificationMoney"
          label="未销金额"
          align="center"
          showOverflowTooltip
          width="100"
        >
        </el-table-column>
        <el-table-column
          prop="bankAccount"
          label="银行账号"
          align="center"
          width="100"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="bankAccountName"
          label="银行账户"
          align="center"
          showOverflowTooltip
          width="100"
        >
        </el-table-column>
        <el-table-column
          prop="memo"
          align="center"
          label="备注"
          showOverflowTooltip
        >
        </el-table-column>
      </AppPageTable>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import CashSearchFrom from './components/CashSearchFrom.vue'
import AppPageTable, { useTableOption } from '@/components/AppPageTable2'
import request from '@/public/request'
import dayjs from 'dayjs'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { fileDownload } from '@/public/publicUtils'

const Router = useRouter()

const state = reactive({
  // 查询条件
  query: {
    DocNo: '', //收付款单号
    InvoiceNo: '', //发票号
    BlNo: '', //提单号
    SaleId: '', //业务员
    SmallAmount: '', //起始金额
    BigAmout: '', //截止金额
    EntId: '', //结算对象
    FeeStatus: 0, //核销状态
    BalanceCode: '', //对账单号
    CheckStatus: -2, //审核状态
    Currency: '', //币种
    Memo: '', //备注
    DocDateList: [], //收付款日期
    DocType: 1 //类型 0 付款 1 收款
  },
  //表格数据
  tableData: {
    data: [],
    option: useTableOption()
  },
  tableLoading: false
})
// 获取列表数据
const getList = async () => {
  let query = JSON.parse(JSON.stringify(state.query))
  if (state.query.CheckStatus < 0) {
    query.CheckStatus = ''
  }
  if (state.query.FeeStatus < 0) {
    query.FeeStatus = ''
  }
  query.DocDateList = [
    query.PayStartTime ? query.PayStartTime : '',
    query.PayEndTime ? query.PayEndTime : ''
  ]
  delete query.PayStartTime
  delete query.PayEndTime
  let search = {
    PageIndex: state.tableData.option.page,
    PageSize: state.tableData.option.pageSize,
    ...query
  }
  state.tableLoading = true
  let res = await request.get('/api/doccash/querycashList', search)
  // if (state.query.CheckStatus === '') {
  //   state.query.CheckStatus = -2
  // }
  // if (state.query.FeeStatus === '') {
  //   state.query.FeeStatus = -2
  // }
  res.content.forEach((item) => {
    item.xunVerificationMoney = Math.trunc(
      item.canverificationMoney - item.sumverificationMoney
    )
  })
  state.tableData.data = res.content
  state.tableData.option.total = res.totalElements
  state.tableLoading = false
}
// 重置
const reset = () => {
  state.query = {
    DocNo: '', //收付款单号
    InvoiceNo: '', //发票号
    BlNo: '', //提单号
    SaleId: '', //业务员
    SmallAmount: '', //起始金额
    BigAmout: '', //截止金额
    EntId: '', //结算对象
    FeeStatus: 0, //核销状态
    BalanceCode: '', //对账单号
    CheckStatus: -2, //审核状态
    Currency: '', //币种
    Memo: '', //备注
    DocDateList: [], //收付款日期
    DocType: 1 //类型 0 付款 1 收款
  }
  getList()
}

// 删除销账
const deleWriteOff = async () => {
  if (!state.tableData.option.selected.length) {
    ElMessage.warning('请选择数据')
    return
  }
  let idArray = []
  let flag = true
  for (const iterator of state.tableData.option.selected) {
    if (iterator.sumverificationMoney && iterator.sumverificationMoney != 0) {
      flag = false
      ElMessage.error('已核销数据不能删除')
      break
    }
    idArray.push(iterator.id)
  }
  if (!flag) {
    return
  }
  ElMessageBox.confirm('是否确定执行删除操作？?', '消息提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let res = await request.post('/api/doccash/delete', {
      idArray
    })
    if (res.status) {
      getList()
      ElMessage.success('成功')
    } else {
      ElMessage.warning(res.message)
    }
  })
}

// 下拉框审核点击
const aduitCommand = async (val) => {
  if (!state.tableData.option.selected.length) {
    ElMessage.warning('请选择数据')
    return
  }
  let req = {
    ids: [],
    checkStatus: val
  }
  let flagOfSubmit = true
  for (const iterator of state.tableData.option.selected) {
    if (val == 1) {
      if (iterator.checkStatus > 0) {
        flagOfSubmit = false
        ElMessage.error('只能提交草稿或者驳回状态的数据')
        break
      }
      if (!iterator.entId) {
        flagOfSubmit = false
        ElMessage.error(`单号为${iterator.doccode}的结算对象为空,不能提交`)
        break
      }
      if (!iterator.currency) {
        flagOfSubmit = false
        ElMessage.error(`单号为${iterator.doccode}的实收币种为空,不能提交`)
        break
      }
      if (!iterator.sumtotalmoney || iterator.sumtotalmoney == 0) {
        flagOfSubmit = false
        ElMessage.error(`单号为${iterator.doccode}的实收金额为空,不能提交`)
        break
      }
      if (!iterator.docdate) {
        flagOfSubmit = false
        ElMessage.error(`单号为${iterator.doccode}的收款日期为空,不能提交`)
        break
      }
      if (!iterator.feeCurrency) {
        flagOfSubmit = false
        ElMessage.error(`单号为${iterator.doccode}的销帐币种为空,不能提交`)
        break
      }
      if (!iterator.exchangeRate || iterator.exchangeRate == 0) {
        flagOfSubmit = false
        ElMessage.error(`单号为${iterator.doccode}的汇率为空,不能提交`)
        break
      }
      if (
        !iterator.sumverificationMoney ||
        iterator.sumverificationMoney == 0
      ) {
        flagOfSubmit = false
        ElMessage.error(`单号为${iterator.doccode}的销帐金额为空,不能提交`)
        break
      }
      if (!iterator.bankAccount) {
        flagOfSubmit = false
        ElMessage.error(`单号为${iterator.doccode}的银行账号为空,不能提交`)
        break
      }
    } else if (val == 2) {
      if (iterator.checkStatus != 1) {
        flagOfSubmit = false
        ElMessage.error('只能审核提交状态的数据')
        break
      }
    } else if (val == -1) {
      if (iterator.checkStatus < 1) {
        flagOfSubmit = false
        ElMessage.error('只能驳回通过、提交的数据')
        break
      }
    }
    req.ids.push(iterator.id)
  }
  if (!flagOfSubmit) {
    return
  }
  let res = await request.post('/api/doccash/checkTable', req)
  if (res.status) {
    getList()
    ElMessage.success('成功')
  } else {
    ElMessage.warning(res.message)
  }
}

// 跳转收款编辑页面
const toEditPage = (row) => {
  Router.openTab({
    path: '/financial/cashDetail',
    query: {
      id: row.id,
      title: '收款详情' + row.doccode,
      iscash: true
    }
  })
}

// 导出excel
const downloadFile = async () => {
  let feeParams = []
  let query = JSON.parse(JSON.stringify(state.query))
  if (query.CheckStatus < 0) {
    query.CheckStatus = ''
  }
  if (query.FeeStatus < 0) {
    query.FeeStatus = ''
  }
  query.DocDateList = [
    query.PayStartTime ? query.PayStartTime : '',
    query.PayEndTime ? query.PayEndTime : ''
  ]
  delete query.PayStartTime
  delete query.PayEndTime
  fileDownload('/api/doccash/download', query, '收款销账')
    .then(() => {})
    .catch((err) => {
      ElMessage.warning('文件导出失败')
    })
}
</script>

<style lang="scss" scoped>
.btn-box {
  margin-bottom: 8px;
}

.doccode-text {
  color: rgb(24, 144, 255);
  // white-space: nowrap;
  // overflow: hidden;
  // text-overflow: ellipsis;
  cursor: pointer;
}
</style>
